<template>
  <n-collapse
    v-model:expanded-names="expandedNames"
    display-directive="show"
    :accordion="accordion">
    <n-collapse-item
      v-for="group in formGroups"
      :key="group.name"
      :name="group.name"
      :disabled="group.disabled">
      <template #arrow><span></span></template>
      <template #header>
        <component :is="group.renderIcon?.(!!expandedNames.includes(group.name))" />
        <template v-if="group.renderTitle">
          <component :is="group.renderTitle(!!expandedNames.includes(group.name))" />
        </template>
        <span v-else style="font-size: 16px">{{ group.title }}</span>
      </template>
      <template #header-extra>
        <template v-if="group.renderArrow">
          <component :is="group.renderArrow(!!expandedNames.includes(group.name))" />"
        </template>
        <n-icon
          v-else
          :component="ChevronLeft16Regular"
          :size="20"
          :style="{
            transition: 'transform 0.3s',
            transform: expandedNames.includes(group.name) ? 'rotate(-90deg)' : '',
          }" />
      </template>
      <form-items
        v-model="form"
        :items="group?.items"
        :cols
        :x-gap
        :y-gap
        :feedback-class
        :feedback-style />
    </n-collapse-item>
  </n-collapse>
</template>

<script lang="ts" setup>
import { ref, computed, type CSSProperties } from "vue";
import { NCollapse, NCollapseItem, NIcon } from "naive-ui";
import { ChevronLeft16Regular } from "@vicons/fluent";
import FormItems from "./FormItems.vue";
import { placeholderType } from "@/_utils";
import type { NaiveFormGroupItem } from "./interface";
import type { RowData } from "@/_interface";

const form = defineModel<RowData>({ required: true });

const props = defineProps<{
  accordion?: boolean;
  cols?: number;
  xGap?: number;
  yGap?: number;
  feedbackClass?: string;
  feedbackStyle?: string | CSSProperties;
  group?: NaiveFormGroupItem<any>[];
}>();

const formGroups = computed(() => {
  if (!props.group) return null;
  return props.group.map((groupItem, idx) => ({
    ...groupItem,
    name: `group-${idx}`,
    items: groupItem.items.map((item) => ({
      ...item,
      placeholder: `${placeholderType(item.type)} ${item.label}`,
    })),
  }));
});
const expandedNames = ref<string[]>(
  formGroups.value ? formGroups.value.filter((item) => item.expanded).map((item) => item.name) : []
);
</script>
